#include "PCH.h"
#include "device_dx9.h"
#include "VertexBufferDX9.h"
#include "IndexBufferDX9.h"
#include "VertexDeclDX9.h"
#include "enum_convert_dx9.h"
using namespace Graphic;

VertexBuffer* Graphic::DeviceDX9::CreateVertexBuffer( int size, int usage, const char* data)
{
	if(size == 0)
		return 0;

	/*
	typedef struct D3DVERTEXELEMENT9 {
	WORD Stream;
	WORD Offset;
	BYTE Type;
	BYTE Method;
	BYTE Usage;
	BYTE UsageIndex;
	} D3DVERTEXELEMENT9, *LPD3DVERTEXELEMENT9;
	*/
	D3D9VertexBuffer* pVertexBuffer = 0;
	if( FAILED(m_pDevice->CreateVertexBuffer(
		size,				//buffer size
		BU_To_BufferCreate_DX9(usage),				//buffer usage
		0,					//FVF
		D3DPOOL_DEFAULT,	//pool
		&pVertexBuffer,		//vb pointer
		0)))				//shared handle
	{
		return 0;
	}
	else
	{
		VertexBuffer* pVB = new VertexBufferDX9(pVertexBuffer, size, data);
		return pVB;
	}
}


IndexBuffer* Graphic::DeviceDX9::CreateIndexBuffer( int size, int usage, const char* data)
{
	if(size == 0)
		return 0;
	D3DFORMAT format = D3DFMT_INDEX16;
	D3D9IndexBuffer* pIndexBuffer = 0;
	if( FAILED(m_pDevice->CreateIndexBuffer(
		size,				//buffer size
		BU_To_BufferCreate_DX9(usage),				//buffer usage
		format,					//FVF
		D3DPOOL_DEFAULT,	//pool
		&pIndexBuffer,		//vb pointer
		0)))				//shared handle
	{
		return 0;
	}
	else
	{
		IndexBuffer* pIB = new IndexBufferDX9(pIndexBuffer, size, data);
		return pIB;
	}

}


VertexDecl* Graphic::DeviceDX9::CreateVertexDecl()
{
	return 0;
	/*
	not completed yet.
	*/
	D3D9VertexDecl* pVertexDecl = 0;
	D3DVERTEXELEMENT9 declArray[] = {
		 D3DDECL_END()
	};
	if( FAILED(m_pDevice->CreateVertexDeclaration(
		declArray,
		&pVertexDecl		
		)))
	{
		return 0;
	}
	else
	{
		int size = sizeof(declArray) - 1;
		VertexDecl* pDecl = new VertexDeclDX9(pVertexDecl, size);
		return pDecl;
	}
	
}



void Graphic::DeviceDX9::SetIndexBuffer( IndexBuffer* ib )
{
	m_pDevice->SetIndices((D3D9IndexBuffer*)ib->GetHandle());
}




void Graphic::DeviceDX9::SetVertexBuffer(int index, VertexBuffer* vb, int base)
{
	m_pDevice->SetStreamSource(
		index,
		(D3D9VertexBuffer*)vb->GetHandle(),
		base,
		0);		//stride
}



void Graphic::DeviceDX9::SetVertexDecl( VertexDecl* decl )
{
	m_pDevice->SetVertexDeclaration((D3D9VertexDecl*)decl->GetHandle());
}
